﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ogdi.Azure.Configuration;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Threading;
using System.Text;
using System.Configuration;

namespace Ogdi.InteractiveSdk.Mvc.Controllers
{
    public class DownloadsController : Controller
    {

        public ActionResult Index()
        {

            var blobClient = GetOgdiConfigBlobClient();
            CreateDownloadPageContainer(blobClient, "downloadpage");
            string parentCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            var localizedFileURI = GetLocalizedFileUri(blobClient, parentCulture, "downloadpage","DownloadsPageContent");
            var cloudBlob = blobClient.GetBlobReference(localizedFileURI);
            Byte[] content = null;
            try
            {
                content = cloudBlob.DownloadByteArray();
            }
            catch (StorageClientException)
            {
                //If the localized page can't be found we search for the default page.
                cloudBlob = blobClient.GetBlobReference(GetLocalizedFileUri(blobClient, "en", "downloadpage", "DownloadsPageContent"));
                content = cloudBlob.DownloadByteArray();
            }
            string htmlContent = Encoding.GetEncoding("ISO-8859-1").GetString(content);
            ViewBag.Htmlcontent = htmlContent;
            return View();
        }

        /// <summary>
        /// Get the Windows Azure Blob client linked to the OgdiConfig storage account
        /// </summary>
        /// <returns>Windows Azure Blob client linked to the OgdiConfig storage account</returns>
        private CloudBlobClient GetOgdiConfigBlobClient()
        {
            var blobStorageEndpoint = ConfigurationManager.AppSettings["BlobStorageEndpoint"];
            var accountName = ConfigurationManager.AppSettings["AccountName"];
            var accountKey = ConfigurationManager.AppSettings["AccountSharedKey"];
            var credentials = new StorageCredentialsAccountAndKey(accountName, accountKey);
            var configAccount = new CloudStorageAccount(credentials, false);
            var client = configAccount.CreateCloudBlobClient();
            return client;
        }

        /// <summary>
        /// Create the CloudBlobContainer if it doesn't exist yet. 
        /// It will contain the differents download pages for each culture.
        /// </summary>
        /// <param name="blobClient">Windows Azure Blob client linked to the OgdiConfig storage account</param>
        /// <param name="containerName">The name of the container which will contain localized pages</param>
        private void CreateDownloadPageContainer(CloudBlobClient blobClient, string containerName)
        {
            var container = blobClient.GetContainerReference(containerName);
            container.CreateIfNotExist();
            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
            container.SetPermissions(permissions);
        }

        /// <summary>
        /// Get the URI of a localized page.
        /// </summary>
        /// <param name="client">Windows Azure Blob client linked to the OgdiConfig storage account</param>
        /// <param name="culture">The invariant culture for which you want the localized page</param>
        /// <param name="containerName">The name of the container which contains the localized pages</param>
        /// <param name="fileName">the name of the localized page</param>
        /// <returns>Absolute URI to the localized page</returns>
        private string GetLocalizedFileUri(CloudBlobClient client, string culture, string containerName, string fileName)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(client.BaseUri.ToString());
            builder.Append(containerName);
            builder.Append('/');
            builder.Append(fileName);
            if (culture != "en")
            {
                builder.Append('.');
                builder.Append(culture);            
            }
            builder.Append(".html");
            return builder.ToString();
        }
    }
}
